const app = getApp();
const api = require("../../utils/api");

Page({
    data: {
        navBarHeight: 0, //顶部导航高度

        shopId: '',
        isShow: false, //是否显示内容（防止出现空白）

        shopcartList: [],
        noContent: false,

        isAllSelected: true, //是否全选
        totalProduct: 0, //购物车商品条数
        totalPrice: 0, //价格合计
        totalNumber: 0, //数量合计
    },
    onLoad(options) {
        const systemInfo = wx.getSystemInfoSync();
        this.setData({
            navBarHeight: systemInfo.statusBarHeight + 44,
        });
        this.initData();
    },
    onShow() {
        if(app.globalData.isRefreshShopcart) {
            this.initData();
            app.globalData.isRefreshShopcart = false;
        }
    },

    initData() { //初始化数据
        this.getShopcartList();
    },
    
    getShopcartList() { //获取购物车列表
        api.post('/order/cart/list')
            .then(res => {
                let list = [];
                let totalProduct = 0; //商品条数
                //整理列表，增加需要的字段
                res.forEach(item => {
                    item.selected = false; //店铺全选标识
                    item.hasProductSelected = false; //店铺是否有商品被选择标识
                    item.detailList.forEach(pro => {
                        pro.selected = false; //商品被选标识
                        pro.price = pro.price.toFixed(2);
                        totalProduct++;
                    });
                    list.push(item);
                });

                this.setData({
                    shopcartList: list,
                    totalProduct: totalProduct,
                    noContent: list.length == 0 ? true : false,
                });
                this.dealSummary(1);
            })
    },
    dealSummary(type = 0) { //计算商品总数
        let sum = 0; //总件数
        let price = 0; //总价格
        let selectedNum = 0; //选中的数量
        
        let list = this.data.shopcartList;
        list.forEach(item => {
            item.detailList.forEach(pro => {
                if(pro.selected) {
                    sum = sum + pro.quantity;
                    price = price + parseFloat(parseFloat(pro.price) * pro.quantity);
                    selectedNum++;
                }
            })
        });
        this.setData({
            totalNumber: sum,
            totalPrice: price.toFixed(2),
            isAllSelected: selectedNum > 0 && selectedNum == this.data.totalProduct ? true : false
        });
        if(type == 0) {
            app.globalData.isRefreshShopcart = true;
        }
    },

    //操作商品数量
    quantityPlus(e) { //数量加
        let index = e.currentTarget.dataset.index;
        let productIndex = e.currentTarget.dataset.idx;
        if(this.data.shopcartList[index].detailList[productIndex].quantity >= this.data.shopcartList[index].detailList[productIndex].limitQuantity) {
            wx.showToast({
                title: `该商品限购${this.data.shopcartList[index].detailList[productIndex].limitQuantity}件！`,
                icon: 'none'
            });
            return;
        }

        this.dealQuantity(index, productIndex);
    },
    quantityMinus(e) { //数量减
        let index = e.currentTarget.dataset.index;
        let productIndex = e.currentTarget.dataset.idx;
        let number = this.data.shopcartList[index].detailList[productIndex].quantity;

        if(number == 1) { //数量为1，询问是否删除
            let item = this.data.shopcartList[index].detailList[productIndex];
            wx.showModal({
                title: '温馨提示',
                content: `您是否确认删除商品【${item.productName}】？`,
                success: res => {
                    if(res.confirm) {
                        this.deleteProduct(index, productIndex);
                    }
                }
            });
        } else {
            this.dealQuantity(index, productIndex, -1);
        }
    },
    dealQuantity(index, productIndex, quantity = 1) { //提交修改商品数量
        let list = this.data.shopcartList;
        api.post(`/order/cart/quantity?id=${list[index].detailList[productIndex].id}&diffQuantity=${quantity}`)
            .then(() => {
                let number = list[index].detailList[productIndex].quantity;
                this.setData({
                    [`shopcartList[${index}].detailList[${productIndex}].quantity`]: number + quantity, //修改数量
                });
                this.dealSummary(); //重新计算商品总数
            })
    },

    deleteProduct(index, productIndex) { //删除商品(单个删除)
        let list = this.data.shopcartList;
        api.post(`/order/cart/remove?ids=${list[index].detailList[productIndex].id}`)
            .then(() => {
                list[index].detailList.splice(productIndex, 1); //删除该条商品
                if(list[index].detailList.length == 0) {
                    list.splice(index, 1); //如果店铺没有商品，删除店铺
                }
                this.setData({
                    shopcartList: list,
                    noContent: list.length == 0 ? true :false,
                });

                wx.showToast({
                    title: '删除成功',
                    icon: 'none'
                });
                this.dealSummary();
            })
    },
    deleteProductBySelected() { //批量所选商品(批量删除)
        wx.showModal({
            title: '温馨提示',
            content: `您是否确认删除所有已勾选的商品？`,
            success: res => {
                if(res.confirm) {
                    let ids = [];
                    this.data.shopcartList.forEach(item => {
                        item.detailList.forEach(pro => {
                            if(pro.selected) {
                                ids.push(pro.id)
                            }
                        });
                    });
                    api.post(`/order/cart/remove?ids=${ids.toString()}`)
                        .then(() => {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'none'
                            });
                            this.setData({
                                shopcartList: [],
                                noContent: true
                            });
                            this.dealSummary();
                        })
                }
            }
        });
    },

    //选择操作
    selectStore(e) { //选择店铺
        let index = e.currentTarget.dataset.index;
        let list = this.data.shopcartList;
        if(this.data.shopcartList[index].selected) { //原来是选中的情况
            list.forEach((item, idx) => {
                //清除选中
                if(idx == index) {
                    item.selected = false;
                    item.hasProductSelected = false;
                    item.detailList.forEach(pro => {
                        pro.selected = false;
                    });
                }
            });
        } else {
            list.forEach((item, idx) => {
                if(idx == index) {
                    //全部选中
                    item.selected = true;
                    item.hasProductSelected = true;
                    item.detailList.forEach(pro => {
                        pro.selected = true;
                    });
                }
            });
        }

        this.setData({
            shopcartList: list
        });
        this.dealSummary();
    },
    selectProduct(e) { //单选or取消单选商品
        let index = e.currentTarget.dataset.index;
        let productIndex = e.currentTarget.dataset.idx;
        let choose = this.data.shopcartList[index].detailList[productIndex].selected;
        this.setData({
            [`shopcartList[${index}].detailList[${productIndex}].selected`]: !choose,
        });

        //判断当前店铺是否全选
        let list = this.data.shopcartList[index].detailList;
        let selectedNum = 0; //店铺商品选中条数
        list.forEach(pro => {
            if(pro.selected) {
                selectedNum++;
            }
        });
        this.setData({
            [`shopcartList[${index}].selected`]: selectedNum == list.length ? true : false,
            [`shopcartList[${index}].hasProductSelected`]: selectedNum > 0 ? true : false,
        });

        this.dealSummary();
    },
    selectAll() { //点击全选
        let list = this.data.shopcartList;
        if(this.data.isAllSelected) { //原来是全选的情况
            list.forEach(item => {
                item.selected = false;
                item.hasProductSelected = false;
                item.detailList.forEach(pro => {
                    pro.selected = false;
                });
            })
        } else {
            list.forEach(item => {
                item.selected = true;
                item.hasProductSelected = true;
                item.detailList.forEach(pro => {
                    pro.selected = true;
                });
            })
        }
        this.setData({
            shopcartList: list
        });
        this.dealSummary();
    },
    
    viewProductDetail(e) { //跳转商品详情
        let item = e.currentTarget.dataset.item;
        if(item.shopId) {
            wx.navigateTo({
                url: `/pages/storeCategoryProduct/storeCategoryProduct?id=${item.productSkuSaleId}&shopId=${item.shopId}`,
            });
        } else {
            wx.navigateTo({
                url: `/pages/productDetail/productDetail?id=${item.productSkuSaleId}&shopId=0`,
            });
        }
    },

    //底部操作栏
    gotoCheck() { //去结算
        if(this.data.totalNumber == 0) {
            wx.showToast({
                title: '请选择要结算的商品!',
                icon: 'none'
            });
            return;
        }

        //检查是否有会员
        if(app.globalData.userInfo.phone == '') {
            wx.showModal({
                title: '温馨提示',
                content: `请先完成会员注册！`,
                success: res => {
                    if(res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login?dir=1',
                        });
                    }
                }
            });
            return;
        }

        //检查是否选了多个店铺
        let shopSelected = 0; //有商品被选的店铺的数量
        this.data.shopcartList.forEach(item => {
            if(item.hasProductSelected) {
                shopSelected++;
            }
        });
        if(shopSelected > 1) {
            wx.showToast({
                title: '每次下单只能选择同一家店铺的商品进行操作!',
                icon: 'none'
            });
            return;
        }
        let shopIndex = this.data.shopcartList.findIndex(item => {
            return item.hasProductSelected;
        });
        this.setData({
            shopId: this.data.shopcartList[shopIndex].shopId, //记录店铺id
        });
        
        //检查是否有限购
        for(let i = 0; i < this.data.shopcartList[shopIndex].detailList.length; i++) {
            if(this.data.shopcartList[shopIndex].detailList[i].limitQuantity && this.data.shopcartList[shopIndex].detailList[i].quantity > this.data.shopcartList[shopIndex].detailList[i].limitQuantity) {
                wx.showToast({
                    title: '有商品超过限购数量，请重新设置!',
                    icon: 'none'
                });
                
                return;
            }
        }

        //缓存选择要下单的商品
        let list = [];
        this.data.shopcartList.forEach(item => {
            if(item.hasProductSelected) {
                item.detailList.forEach(pro => {
                    if(pro.selected) {
                        list.push(pro);
                    }
                });
            }
        });
        app.globalData.shopcartCacheList = list;
        //跳转结算页面
        wx.navigateTo({
            url: `/pages/orderConfirm/orderConfirm?shopId=${this.data.shopId}&dir=${this.data.shopId ? 0 : 1}`,
        });
    },
})